package hesso.smartdraw.ch;

import java.util.ArrayList;

import hesso.smartdraw.ch.db.DBHelper;
import hesso.smartdraw.ch.guielements.ButtonSprite;
import hesso.smartdraw.ch.guielements.DeviceScreenElement;
import hesso.smartdraw.ch.guielements.TextOnScreen;
import hesso.smartdraw.ch.guielements.WallFloor;
import hesso.smartdraw.ch.guielements.WallScreenElement;
import hesso.smartdraw.ch.model.Installed;
import hesso.smartdraw.ch.model.Room;
import hesso.smartdraw.ch.model.Wall;
import hesso.smartdraw.ch.multitouch.MultiTouch;
import hesso.smartdraw.ch.multitouch.MultiTouchException;
import hesso.smartdraw.ch.multitouch.PinchZoomDetector;
import hesso.smartdraw.ch.multitouch.PinchZoomDetector.IPinchZoomDetectorListener;

import org.anddev.andengine.engine.Engine;
import org.anddev.andengine.engine.camera.ZoomCamera;
import org.anddev.andengine.engine.camera.hud.HUD;
import org.anddev.andengine.engine.options.EngineOptions;
import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation;
import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy;
import org.anddev.andengine.entity.scene.Scene;
import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener;
import org.anddev.andengine.entity.scene.background.ColorBackground;
import org.anddev.andengine.entity.util.FPSLogger;
import org.anddev.andengine.input.touch.TouchEvent;
import org.anddev.andengine.input.touch.detector.ScrollDetector;
import org.anddev.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.anddev.andengine.input.touch.detector.SurfaceScrollDetector;
import org.anddev.andengine.opengl.font.Font;
import org.anddev.andengine.opengl.texture.Texture;
import org.anddev.andengine.opengl.texture.TextureOptions;
import org.anddev.andengine.opengl.texture.region.TextureRegion;
import org.anddev.andengine.opengl.texture.region.TextureRegionFactory;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Display;
import android.widget.Toast;

/**
 * @author Nicolas Gramlich
 * @since 15:44:58 - 05.11.2010
 */
public class AddDeviceScreen extends Base implements IOnSceneTouchListener, IScrollDetectorListener, IPinchZoomDetectorListener {
	// ===========================================================
	// Constants
	// ===========================================================

	// ===========================================================
	// Fields
	// ===========================================================

	private ZoomCamera mZoomCamera;

	private Texture mTexture;
	private TextureRegion mFaceTextureRegion;

	private Display display;

	private SurfaceScrollDetector mScrollDetector;
	private PinchZoomDetector mPinchZoomDetector;
	private float mPinchZoomStartedCameraZoomFactor;
	
	private DBHelper dbHelper;

	private Room room;
	
	private int roomId;
	
	private int buildingId;

	private  ArrayList<DeviceScreenElement> devices;
	private  ArrayList<TextOnScreen> descriptions;

	private boolean editMode = false;

	private int currentWallIndex = 0;

	private WallScreenElement wall;
	
	private Texture deviceTexture;
	
	private TextureRegion deviceTextureRegion;
	
	private Texture mFontTexture;
	
	private Font mFont;
	
	private WallFloor wallFloor;
	
	private boolean wallFloorIsDrawed = false;
	
	private int level;
	
	private int x;
	private int y;

	// ===========================================================
		// Constructors
		// ===========================================================

	// ===========================================================
	// Getter & Setter
	// ===========================================================

	// ===========================================================
	// Methods for/from SuperClass/Interfaces
	// ===========================================================

	@Override
	public Engine onLoadEngine() {

		display = getWindowManager().getDefaultDisplay(); 

		this.mZoomCamera = new ZoomCamera(0, 0, display.getWidth(), display.getHeight());
		final Engine engine = new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(display.getWidth(), display.getHeight()), this.mZoomCamera));

		
		
		return engine;
	}

	@Override
	public void onLoadResources() {

		
		deviceTexture = new Texture(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
        deviceTextureRegion = TextureRegionFactory.createFromAsset(deviceTexture, this, "icons/deviceIcon.png", 0, 0);
        
        this.mFontTexture = new Texture(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFont = new Font(mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 12, true, Color.BLACK);
		this.mEngine.getTextureManager().loadTexture(this.mFontTexture);
        this.mEngine.getFontManager().loadFont(this.mFont);
        this.mEngine.getTextureManager().loadTexture(deviceTexture);
		
		final Bundle extras = getIntent().getExtras();
    	this.roomId = extras.getInt("roomId");
//    	this.levelId = extras.getInt("levelId");
    	this.buildingId = extras.getInt("buildingId");
    	this.level = extras.getInt("level");
        this.currentWallIndex = extras.getInt("currentWallIndex");

        
  	
    	dbHelper = DBHelper.getInstance(this);

    	room = dbHelper.getRoomByRoomId(roomId);
    	
	}

	@Override
	public Scene onLoadScene() {
		this.mEngine.registerUpdateHandler(new FPSLogger());

		final Scene scene = new Scene(1);
		scene.setOnAreaTouchTraversalFrontToBack();

		loadWall(scene);

		scene.setBackground(new ColorBackground(0.2980f, 0.5372f, 0.7294f));

		this.mScrollDetector = new SurfaceScrollDetector(this);
		if(MultiTouch.isSupportedByAndroidVersion()) {
			try {
				this.mPinchZoomDetector = new PinchZoomDetector(this);
			} catch (final MultiTouchException e) {
				this.mPinchZoomDetector = null;
			}
		} else {
			this.mPinchZoomDetector = null;
		}

		scene.setOnSceneTouchListener(this);
		scene.setTouchAreaBindingEnabled(true);

		HUD hud = new HUD();

		mZoomCamera.setHUD(hud);

		this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/editIcon.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mTexture);

		ButtonSprite changetoEditModeButton = new ButtonSprite(10,10,this.mFaceTextureRegion) {

			@Override
			public void actionUp() {
				if(editMode) {

					Toast.makeText(AddDeviceScreen.this, "You are already in Edit Mode", Toast.LENGTH_SHORT).show();    

				} else {

					editMode = true;
					Toast.makeText(AddDeviceScreen.this, "Edit Mode", Toast.LENGTH_SHORT).show();

				};  
			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}
		};

		this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/viewIcon.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mTexture);

		ButtonSprite changetoViewModeButton = new ButtonSprite(84,10,this.mFaceTextureRegion) {

			@Override
			public void actionUp() {
				if(editMode) {
					editMode = false;
					Toast.makeText(AddDeviceScreen.this, "View Mode", Toast.LENGTH_SHORT).show();    

				} else {

					Toast.makeText(AddDeviceScreen.this, "You are already in View Mode", Toast.LENGTH_SHORT).show();

				};  
			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}
		};

		this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/wallsIcon.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mTexture);
		ButtonSprite goBackButton = new ButtonSprite(display.getWidth() - 74,10,this.mFaceTextureRegion) {

			@Override
			public void actionUp() {
				Intent intent = new Intent(AddDeviceScreen.this, DrawWallScreen.class);

				intent.putExtra("buildingId", buildingId);
            	intent.putExtra("level", level);
				startActivity(intent);
				
			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}
		};

	
		
		this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/forwardIcon.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mTexture);

		ButtonSprite forwardButton = new ButtonSprite(display.getWidth() - 74,display.getHeight() - 74,this.mFaceTextureRegion) {

			@Override
			public void actionUp() {
				currentWallIndex++;
				loadWall(scene);
				
			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}
		};
		
		this.mTexture = new Texture(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA);
		this.mFaceTextureRegion = TextureRegionFactory.createFromAsset(this.mTexture, this, "icons/backwardIcon.png", 0, 0);
		this.mEngine.getTextureManager().loadTexture(this.mTexture);

		ButtonSprite backwardButton = new ButtonSprite(10,display.getHeight() - 78,this.mFaceTextureRegion) {

			@Override
			public void actionUp() {
				currentWallIndex--;
				loadWall(scene);
				
			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}
		};

		

		hud.attachChild(changetoEditModeButton);
		hud.registerTouchArea(changetoEditModeButton);
		hud.attachChild(changetoViewModeButton);
		hud.registerTouchArea(changetoViewModeButton);
		hud.attachChild(goBackButton);
		hud.registerTouchArea(goBackButton);

		hud.attachChild(forwardButton);
		hud.registerTouchArea(forwardButton);

		hud.attachChild(backwardButton);
		hud.registerTouchArea(backwardButton);

		return scene;
	}

	@Override
	public void onLoadComplete() {

	}

	@Override
	public void onScroll(final ScrollDetector pScollDetector, final TouchEvent pTouchEvent, final float pDistanceX, final float pDistanceY) {
		final float zoomFactor = this.mZoomCamera.getZoomFactor();
		this.mZoomCamera.offsetCenter(-pDistanceX / zoomFactor, -pDistanceY / zoomFactor);
	}

	@Override
	public void onPinchZoomStarted(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent) {
		this.mPinchZoomStartedCameraZoomFactor = this.mZoomCamera.getZoomFactor();
	}

	@Override
	public void onPinchZoom(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) {
		this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
	}

	@Override
	public void onPinchZoomFinished(final PinchZoomDetector pPinchZoomDetector, final TouchEvent pTouchEvent, final float pZoomFactor) {
		this.mZoomCamera.setZoomFactor(this.mPinchZoomStartedCameraZoomFactor * pZoomFactor);
	}


	@Override
	public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {

		if(editMode) {

			switch(pSceneTouchEvent.getAction()) {

			case TouchEvent.ACTION_DOWN:
				addDevice((int)pSceneTouchEvent.getX(), (int)pSceneTouchEvent.getY(), pScene);
				break;

			case TouchEvent.ACTION_MOVE:

				break;
			case TouchEvent.ACTION_UP:

				break;
			}

		} else {

			if(this.mPinchZoomDetector != null) {
				this.mPinchZoomDetector.onTouchEvent(pSceneTouchEvent);

				if(this.mPinchZoomDetector.isZooming()) {
					this.mScrollDetector.setEnabled(false);
				} else {
					if(pSceneTouchEvent.isActionDown()) {
						this.mScrollDetector.setEnabled(true);
					}
					this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
				}
			} else {
				this.mScrollDetector.onTouchEvent(pSceneTouchEvent);
			}
		}



		return true;
	}

	// ===========================================================
		// Methods
		// ===========================================================

	public void loadWall(Scene scene) {


		if(currentWallIndex < 0) {
			currentWallIndex = room.getWallArray().size()-1;
		} else if (currentWallIndex == room.getWallArray().size()) {
			currentWallIndex = 0;
		}
		
		

		if(wall != null) {

			scene.detachChild(wall);

		}
		
		Wall tempWall = room.getWallArray().get(this.currentWallIndex);

		wall = new WallScreenElement(250, 200, tempWall);
		
		
		

			
			this.wallFloor = new WallFloor(scene);
			this.wallFloor.drawWallFloor();
			wallFloorIsDrawed = true;


		scene.attachChild(wall);


		loadDevices(tempWall, scene);
	}

	public void loadDevices(Wall w, Scene scene) {

		if(devices != null) {

			for(DeviceScreenElement d : devices) {

				scene.detachChild(d);
				scene.unregisterTouchArea(d);
			}  
			
			for(TextOnScreen t : descriptions) {
				
				scene.detachChild(t);
			}
		}

		ArrayList<Installed> tempDevices = w.getInstalledArray();

		devices = new ArrayList<DeviceScreenElement>();
		
		descriptions = new ArrayList<TextOnScreen>();

		for(final Installed d : tempDevices) {

			DeviceScreenElement tempDeviceElement =
				new DeviceScreenElement(d.getX(), d.getY(), deviceTextureRegion) {

				@Override
				public void actionDown() {
					// TODO Auto-generated method stub

				}

				@Override
				public void actionMove() {
					// TODO Auto-generated method stub

				}

				@Override
				public void actionUp() {

					Intent intent = new Intent(AddDeviceScreen.this,EditDeviceScreen.class);
					intent.putExtra("roomId", roomId);
					intent.putExtra("currentWallIndex", currentWallIndex);
					intent.putExtra("installedId", d.getId());
					intent.putExtra("buildingId", buildingId);
					intent.putExtra("level", level);
					intent.putExtra("x", d.getX());
					intent.putExtra("y", d.getY());
					startActivity(intent);
				}

			};
			
		
			 
			TextOnScreen text = new TextOnScreen(d.getX(), d.getY() - 15, mFont, d.getDevice().getName());
			descriptions.add(text);
			devices.add(tempDeviceElement);
			scene.attachChild(text);
			scene.attachChild(tempDeviceElement);
			scene.registerTouchArea(tempDeviceElement);
		}
	}

	public void addDevice(final int x, final int y, Scene scene) {
		 
		 TextOnScreen text = new TextOnScreen(x, y - 15, mFont, "Description");

		// Wall wall = room.getWallArray().get(this.currentWallIndex);
		DeviceScreenElement tempDevice = new DeviceScreenElement(x, y, deviceTextureRegion){

			@Override
			public void actionDown() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionMove() {
				// TODO Auto-generated method stub

			}

			@Override
			public void actionUp() {
				Intent intent = new Intent(AddDeviceScreen.this,EditDeviceScreen.class);
				intent.putExtra("roomId", roomId);
				intent.putExtra("currentWallIndex", currentWallIndex);
				intent.putExtra("level", level);
				intent.putExtra("installedId", -1);
				intent.putExtra("buildingId", buildingId);
				intent.putExtra("x", x);
				intent.putExtra("y", y);
				startActivity(intent);
				
			}

		};
		
		Wall tempWall = room.getWallArray().get(this.currentWallIndex);
		devices.add(tempDevice);
		descriptions.add(text);
		
		scene.attachChild(text);
		scene.attachChild(tempDevice);
		scene.registerTouchArea(tempDevice);
	}

	// ===========================================================
	// Inner and Anonymous Classes
	// ===========================================================
}